Skip to content

Quote a field even when its encoding is invalid - #404

Open
adityawrk wants to merge 2 commits into
ruby:mainfrom
adityawrk:fix/quote-invalid-encoding
Open

adityawrk wants to merge 2 commits into
ruby:mainfrom
adityawrk:fix/quote-invalid-encoding

Conversation

@adityawrk

Copy link
Copy Markdown

Fixes #395.

The writer quoted a field when it contained a newline, a comma, or a quote. That check used a regexp, and Regexp#match? raises on an invalid byte, so the code skipped the check whenever valid_encoding? was false and wrote the field raw.

A UTF-8 field "x\xFF\nadmin,true" was emitted as two lines. The same text without the bad byte, and the same bytes tagged as ASCII-8BIT, were quoted. Shift_JIS and EUC-JP did the same. A byte-oriented reader then saw a row the writer never produced:

before: "user,x\xFF\nadmin,true,role\n"
        => [["user", "x\xFF"], ["admin", "true", "role"]]
after:  "user,\"x\xFF\nadmin,true\",role\n"
        => [["user", "x\xFF\nadmin,true", "role"]]

An invalid field that contains none of those characters is still written unquoted. A field that also contains a quote still doubles it. The full suite passes with and without CSV_PARSER_SCANNER_TEST=yes (537 tests, 4092 assertions).

A UTF-8, Shift_JIS, or EUC-JP field with one bad byte and a
newline, comma, or quote was written raw. The same field
without the bad byte was quoted, so a consumer that accepts
the byte saw an extra row.
The quote check skipped the regexp when valid_encoding? was
false, because match? raises. The field was then written raw,
so a newline or comma inside it became another row. The check
now looks for those bytes with String#include?.

Fixes ruby#395

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CSV writer emits invalid-encoding fields unquoted, allowing row and column injection

1 participant